//
//  MSImproveUserInfoVC.m
//  MS
//
//  Created by Yuan on 13-4-1.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSImproveUserInfoVC.h"
#import "MSAppDelegate.h"
#import "UIColor+ColorUtils.h"

@interface MSImproveUserInfoVC ()<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    UITableView *tbView;
    UIPickerView *pickerView;
    
    NSMutableDictionary *userInfo;
    
    NSMutableDictionary *provices;

    NSMutableArray *proviceArray;
    NSMutableArray *areasArray;
    NSString *proviceName;
    NSString *cityName;
    NSInteger compoentOneSelectedIndex;
    NSInteger compoentTwoSelectedIndex;
}
@property(nonatomic,retain)UITableView *tb;
@property(nonatomic,retain)UIPickerView *pickerView;
@property(nonatomic,retain)NSMutableDictionary *userInfo;
@property(nonatomic,retain)NSMutableDictionary *provices;
@property(nonatomic,retain)NSMutableArray *proviceArray;
@property(nonatomic,retain)NSMutableArray *areasArray;
@end

@implementation MSImproveUserInfoVC
@synthesize tb;
@synthesize pickerView;
@synthesize provices;
@synthesize userInfo;
@synthesize proviceArray;
@synthesize areasArray;

-(void)dealloc
{
    self.tb = nil;
    self.pickerView = nil;
    userInfo = nil;
    areasArray = nil;
    proviceArray = nil;
    pickerView = nil;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        proviceName = @"";  cityName = @"";
        compoentOneSelectedIndex = 0; compoentTwoSelectedIndex = 0;

        userInfo = [[NSMutableDictionary alloc]init];
        
        NSString *path_ = [[NSBundle mainBundle] pathForResource:@"provice" ofType:@"plist"];
        provices = [[NSMutableDictionary alloc]initWithContentsOfFile:path_];
      
        NSArray *pArray = [provices objectForKey:@"provices"];

        NSArray *rArray = [pArray sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2)
                           {
                               NSNumber * id1 = [NSNumber numberWithInt:[[obj1 objectForKey:@"id"] intValue]];
                               NSNumber * id2 = [NSNumber numberWithInt:[[obj2 objectForKey:@"id"] intValue]];
                               NSComparisonResult result = [id2 compare:id1];
                               return result == NSOrderedAscending;
                           }];
        proviceArray = [[NSMutableArray alloc]initWithArray:rArray];
        
        areasArray = [[NSMutableArray alloc]initWithArray:[provices objectForKey:[[proviceArray objectAtIndex:0] objectForKey:@"id"]]];
        
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    CGRect tableViewFrame = CGRectMake(5,10, self.view.frame.size.width-10,self.view.frame.size.height);
    self.tb = [[UITableView alloc]initWithFrame:tableViewFrame style:UITableViewStyleGrouped];
    self.tb.delegate = self;
    self.tb.dataSource = self;
    self.tb.backgroundColor = [UIColor clearColor];
    self.tb.backgroundView = nil;
    [self.view addSubview:self.tb];
    
    UILabel *footerLbl = [MSTool createLable:CGRectMake(0,240, tableViewFrame.size.width, 30)];
    [footerLbl setText:HYLocalizedString(@"为了您能更快完成发型师认证，请输入正确内容")];
    footerLbl.textAlignment = UITextAlignmentCenter;
    [footerLbl setTextColor:[UIColor colorWithString:@"#f376a0"]];
    [self.tb addSubview:footerLbl];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:HYLocalizedString(@"完善发型师信息") showBackButton:NO];
    [self setRightItem:HYLocalizedString(@"完成")];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    UIViewSetFrameHeight(self.tb, self.tb.contentSize.height);

}

-(void)rightBarButtonItemAction:(UIButton *)btn
{    
    if (![userInfo objectForKey:@"city_id"] || ![userInfo objectForKey:@"province_id"])
    {
        return  [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请选择所在区域!")];
    }
    
    UITableViewCell *salonCell = [tb cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITextField *salonTxt = (UITextField*)[salonCell.contentView viewWithTag:2];
    if ([salonTxt.text length]<3)
    {
        return  [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请填写沙龙的全称!")];
    }
    
    UITableViewCell *addressCell = [tb cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    UITextField *addressTxt = (UITextField*)[addressCell.contentView viewWithTag:2];
    
    //    if ([addressTxt.text length]<5)
    //        return  [self showAlert:@"提示" withMes:@"沙龙的详细地址填写错误!"];
    
    UITableViewCell *phoneCell = [tb cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    UITextField *phoneTxt = (UITextField*)[phoneCell.contentView viewWithTag:2];
    
    //    if ([phoneTxt.text length]<11)return  [self showAlert:@"提示" withMes:@"请填写正确的手机号码!"];
    
    [userInfo setObject:[[MSSetting sharedSetting]getAccountID] forKey:@"uid"];
    [userInfo setObject:salonTxt.text forKey:@"salon"];
    if ([phoneTxt.text length]>0)
    {
        [userInfo setObject:phoneTxt.text forKey:@"mobile"];
    }
    
    if ([addressTxt.text length]>0) {
        [userInfo setObject:addressTxt.text forKey:@"address"];
    }
    
    [WebService  getRequestAction:APIUserInfoSet
                            param:userInfo
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             [[MSSetting sharedSetting]setAccountInfo:[info objectForKey:@"result"]];
             [[MSAppDelegate sharedAppDelegate]dismissViewControl];
             [MSTool showAlert:HYLocalizedString(@"完善资料成功!")];
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tb scrollsToTop];
    CGRect sFrame = self.tb.frame;
    sFrame.origin.y = 0.0f;
    [UIView animateWithDuration:0.3 animations:^(void){
        [self.tb setFrame:sFrame];
    }];
    return [textField resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField        // return NO to disallow editing.
{
    UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
    NSIndexPath *indexPath = [self.tb indexPathForCell:cell];
    CGRect sFrame = self.tb.frame;
    if (indexPath.row == 0)
    {
        //city
        sFrame.origin.y = 0.0f;
    }
    else  if (indexPath.row == 1||indexPath.row == 2)
    {
        //salon
        sFrame.origin.y = -40.0f;
    }
    else  if (indexPath.row == 3)
    {
        //mobile
        sFrame.origin.y = -100.0f;
    }
    
    [UIView animateWithDuration:0.3 animations:^(void){
        [self.tb setFrame:sFrame];
    }];
    
    return YES;
}

-(UITextField *)inputTextField
{
    UITextField *textFiled=[[UITextField alloc]initWithFrame:CGRectMake(40.f,0,235.f, 50)];
    //    textFiled.borderStyle=UITextBorderStyleNone;
    textFiled.font = [UIFont systemFontOfSize:16.0f];
    textFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textFiled.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFiled.returnKeyType=UIReturnKeyNext;
    textFiled.delegate=self;
    return textFiled;
}

#pragma mark -UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}

//setting_fav/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier=@"signup";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        UITextField *textFiled=[[UITextField alloc]initWithFrame:CGRectMake(50,0,200, 50)];
        textFiled.font = [UIFont systemFontOfSize:16.0f];
        textFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        textFiled.textAlignment = UITextAlignmentRight;
        textFiled.returnKeyType=UIReturnKeyDone;
        textFiled.textColor = [UIColor colorWithRed:0.000 green:0.180 blue:0.311 alpha:0.950];
        textFiled.delegate=self;
        textFiled.tag = 2;
        
        if (indexPath.row==0)
        {
            pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, 320, 216)];
            pickerView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
            pickerView.dataSource=self;
            pickerView.delegate=self;
            pickerView.showsSelectionIndicator=YES;
            textFiled.inputView = pickerView;
        }
        
        [cell.contentView addSubview:textFiled];
    }
    cell.textLabel.textColor = [UIColor grayColor];
    cell.detailTextLabel.text = @"";
    cell.detailTextLabel.font = [UIFont systemFontOfSize:16.0f];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0.000 green:0.180 blue:0.311 alpha:0.950];
    cell.textLabel.font = [UIFont systemFontOfSize:16.0f];
    UITextField *txt = (UITextField *)[cell.contentView viewWithTag:2];
    txt.hidden = NO;
    switch (indexPath.row)
    {
        case 0:
        {
            txt.hidden = YES;
            cell.detailTextLabel.text = HYLocalizedString(@"请选择城市和地区");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = HYLocalizedString(@"城市");
            txt.placeholder = HYLocalizedString(@"请选择城市和地区");
        }
            break;
        case 1:
        {
            cell.textLabel.text = HYLocalizedString(@"沙龙");
            
            txt.placeholder = HYLocalizedString(@"请填写沙龙名称");
        }
            break;
        case 2:
        {
            cell.textLabel.text = HYLocalizedString(@"地址");
            
            txt.placeholder = HYLocalizedString(@"请填写沙龙的地址");
        }
            break;
        case 3:
        {
            cell.textLabel.text = HYLocalizedString(@"手机");
            
            txt.placeholder = HYLocalizedString(@"请输入您的手机");
        }
            break;
        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UITextField *txt = (UITextField *)[cell.contentView viewWithTag:2];
        [txt becomeFirstResponder];
        if ([proviceName length]<1 || [cityName length] < 1)
        {
            [self pickerView:self.pickerView didSelectRow:compoentOneSelectedIndex inComponent:0];
            [self pickerView:self.pickerView didSelectRow:compoentTwoSelectedIndex inComponent:1];
        }
        [self.pickerView selectRow:compoentOneSelectedIndex inComponent:0 animated:YES];
        [self.pickerView selectRow:compoentTwoSelectedIndex inComponent:1 animated:YES];
    }
}

// Number of wheels
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}

// Number of rows per wheel
- (NSInteger)pickerView: (UIPickerView *)pView numberOfRowsInComponent: (NSInteger) component
{
	if (component == 0)
    {
		return [proviceArray count];
	}
	else if(component ==1)
    {
		return [areasArray count];
	}
	else
    {
		return 0;
	}
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	if (component == 0)
    {
		return [[proviceArray objectAtIndex:row] objectForKey:@"name"];
	}
	else if (component == 1)
    {
		return [[areasArray objectAtIndex:row] objectForKey:@"name"];
	}
	
	return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	NSLog(@"row %d component %d", row, component);
	
    if (component == 0)
    {
        compoentOneSelectedIndex = row;
        
        compoentTwoSelectedIndex = 0;
        
		[areasArray removeAllObjects];
        NSString *pid = [[proviceArray objectAtIndex:row] objectForKey:@"id"];
        
        [userInfo setObject:pid forKey:@"province_id"];
        
		[areasArray addObjectsFromArray:[provices objectForKey:pid]];
		[self.pickerView selectRow:0 inComponent:1 animated:NO];
		[self.pickerView reloadComponent:1];
        proviceName = [[proviceArray objectAtIndex:row] objectForKey:@"name"];
        
        if ([areasArray count]>0)
            cityName = [[areasArray objectAtIndex:0] objectForKey:@"name"];
        
        NSString *cid = [[areasArray objectAtIndex:0] objectForKey:@"id"];
        
        if (cid && [cid length]>0)[userInfo setObject:cid forKey:@"city_id"];
	}
	else if (component == 1)
    {
        compoentTwoSelectedIndex = row;
        
        cityName = [[areasArray objectAtIndex:row] objectForKey:@"name"];
        
        NSString *cid = [[areasArray objectAtIndex:row] objectForKey:@"id"];
        
        if (cid && [cid length]>0)[userInfo setObject:cid forKey:@"city_id"];
	}
    
    HYLog(@"userInfo-->%@",userInfo);
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    UITableViewCell *cell = [tb cellForRowAtIndexPath:indexPath];
    
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",proviceName,cityName];
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	if (component == 0)
    {
		return 80; // province
	}
	else {
		return 240; // crses
	}
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
